package com.thales.sentinel.util;

import Aladdin.Hasp;
import Aladdin.HaspStatus;

/**
 * 许可证数据写入工具类
 * 用于将许可证JSON数据写入加密狗的只读内存区域
 * 注意：这个工具类仅用于演示和测试目的
 * 在生产环境中，只读内存的写入通常在制造时完成
 */
public class LicenseDataWriter {
    
    // 供应商代码 - 与其他类保持一致
    private static final String VENDOR_CODE = new String(
            "AzIceaqfA1hX5wS+M8cGnYh5ceevUnOZIzJBbXFD6dgf3tBkb9cvUF/Tkd/iKu2fsg9wAysYKw7RMA" +
                    "sVvIp4KcXle/v1RaXrLVnNBJ2H2DmrbUMOZbQUFXe698qmJsqNpLXRA367xpZ54i8kC5DTXwDhfxWT" +
                    "OZrBrh5sRKHcoVLumztIQjgWh37AzmSd1bLOfUGI0xjAL9zJWO3fRaeB0NS2KlmoKaVT5Y04zZEc06" +
                    "waU2r6AU2Dc4uipJqJmObqKM+tfNKAS0rZr5IudRiC7pUwnmtaHRe5fgSI8M7yvypvm+13Wm4Gwd4V" +
                    "nYiZvSxf8ImN3ZOG9wEzfyMIlH2+rKPUVHI+igsqla0Wd9m7ZUR9vFotj1uYV0OzG7hX0+huN2E/Id" +
                    "gLDjbiapj1e2fKHrMmGFaIvI6xzzJIQJF9GiRZ7+0jNFLKSyzX/K3JAyFrIPObfwM+y+zAgE1sWcZ1" +
                    "YnuBhICyRHBhaJDKIZL8MywrEfB2yF+R3k9wFG1oN48gSLyfrfEKuB/qgNp+BeTruWUk0AwRE9XVMU" +
                    "uRbjpxa4YA67SKunFEgFGgUfHBeHJTivvUl0u4Dki1UKAT973P+nXy2O0u239If/kRpNUVhMg8kpk7" +
                    "s8i6Arp7l/705/bLCx4kN5hHHSXIqkiG9tHdeNV8VYo5+72hgaCx3/uVoVLmtvxbOIvo120uTJbuLV" +
                    "TvT8KtsOlb3DxwUrwLzaEMoAQAFk6Q9bNipHxfkRQER4kR7IYTMzSoW5mxh3H9O8Ge5BqVeYMEW36q" +
                    "9wnOYfxOLNw6yQMf8f9sJN4KhZty02xm707S7VEfJJ1KNq7b5pP/3RjE0IKtB2gE6vAPRvRLzEohu0" +
                    "m7q1aUp8wAvSiqjZy7FLaTtLEApXYvLvz6PEJdj4TegCZugj7c8bIOEqLXmloZ6EgVnjQ7/ttys7VF" +
                    "ITB3mazzFiyQuKf4J6+b/a/Y");
    
    /**
     * 示例许可证JSON数据
     */
    private static final String SAMPLE_LICENSE_JSON = 
        "{\n" +
        "  \"expirationDate\": \"2026-06-23T23:59:59Z\",\n" +
        "  \"restrictions\": {\n" +
        "    \"maxUsers\": 5,\n" +
        "    \"featureSet\": [\n" +
        "      \"wms\",\n" +
        "      \"iam\",\n" +
        "      \"data_export\"\n" +
        "    ]\n" +
        "  },\n" +
        "  \"licenseAgreement\": {\n" +
        "    \"version\": \"1.0\",\n" +
        "    \"text\": \"This software is licensed for...\"\n" +
        "  }\n" +
        "}";
    
    /**
     * 将许可证数据写入加密狗只读内存
     * 注意：这个方法仅用于演示目的
     * 在实际生产环境中，只读内存通常在制造时写入
     * 
     * @param jsonData 要写入的JSON数据
     * @return 操作结果描述
     */
    public static String writeLicenseData(String jsonData) {
        StringBuilder result = new StringBuilder();
        result.append("许可证数据写入工具\n");
        result.append("警告：此工具仅用于演示和测试目的\n");
        result.append("在生产环境中，只读内存通常在制造时写入\n\n");
        
        Hasp hasp = new Hasp(0);
        
        try {
            // 登录到密钥
            result.append("登录到密钥... ");
            hasp.login(VENDOR_CODE);
            int status = hasp.getLastError();
            
            if (status != HaspStatus.HASP_STATUS_OK) {
                result.append("失败\n");
                result.append("错误码: ").append(status).append("\n");
                result.append(getStatusDescription(status)).append("\n");
                return result.toString();
            }
            result.append("成功\n");
            
            // 检查是否可以写入只读内存
            // 注意：在真实的加密狗中，只读内存通常是真正只读的
            // 这里的写入操作可能会失败
            result.append("\n准备写入数据到只读内存...\n");
            result.append("数据长度: ").append(jsonData.length()).append(" 字节\n");
            
            byte[] dataBytes = jsonData.getBytes("UTF-8");
            
            // 尝试写入数据
            result.append("\n尝试写入数据... ");
            hasp.write(Hasp.HASP_FILEID_RO, 0, dataBytes);
            status = hasp.getLastError();
            
            if (status == HaspStatus.HASP_STATUS_OK) {
                result.append("成功\n");
                result.append("许可证数据已写入加密狗只读内存\n");
            } else {
                result.append("失败\n");
                result.append("错误码: ").append(status).append("\n");
                result.append("可能原因: 只读内存区域不允许写入\n");
                result.append("建议: 使用专用的编程工具或联系硬件供应商\n");
            }
            
        } catch (Exception e) {
            result.append("写入过程中发生异常: ").append(e.getMessage()).append("\n");
        } finally {
            // 登出
            hasp.logout();
            result.append("\n已登出密钥\n");
        }
        
        return result.toString();
    }
    
    /**
     * 获取状态码描述
     */
    private static String getStatusDescription(int status) {
        switch (status) {
            case HaspStatus.HASP_FEATURE_NOT_FOUND:
                return "未找到指定功能";
            case HaspStatus.HASP_HASP_NOT_FOUND:
                return "未找到Sentinel密钥";
            case HaspStatus.HASP_OLD_DRIVER:
                return "驱动版本过旧";
            case HaspStatus.HASP_NO_DRIVER:
                return "未安装驱动";
            case HaspStatus.HASP_INV_VCODE:
                return "无效的供应商代码";
            case HaspStatus.HASP_ACCESS_DENIED:
                return "访问被拒绝";
            default:
                return "未知错误";
        }
    }
    
    /**
     * 主方法 - 用于独立运行此工具
     */
    public static void main(String[] args) {
        System.out.println("Sentinel LDK 许可证数据写入工具");
        System.out.println("================================\n");
        
        String jsonData = SAMPLE_LICENSE_JSON;
        
        if (args.length > 0) {
            // 如果提供了命令行参数，使用第一个参数作为JSON数据
            jsonData = args[0];
        }
        
        System.out.println("将要写入的许可证数据:");
        System.out.println(jsonData);
        System.out.println("\n" + "=".repeat(50) + "\n");
        
        String result = writeLicenseData(jsonData);
        System.out.println(result);
    }
}